import logging
from errorcodes import GeneralError

"""
Module for logging facilities.
"""


class Logger(logging.Logger):
  """
  Base class of loggers, derived from logging.Logger.
  """

  def raiseLog(self, exceptionClass, msg):
    """
    Convenience method for raise an exception after logging the incident.
    """

    self.error(msg)
    raise exceptionClass(msg)  


class Loggable:
  """
  Loggable class that simplifies logging tasks.
  """

  def __init__(self, data, logLevel=None):
    """
    Constructor that accepts an already created instance of Loggable or a
    filename for create a new logger. If filename is provided, the logger
    created is tuned at that the log level given.
    """

    if isinstance(data, logging.Logger):
      # Reuse the existent logger
      self.logger = data.logger
    elif isinstance(data, str):
      # Opens a new logger
      self.logger = Logger()
      fmt = '%(asctime)s %(module)s %(levelname)s %(message)s'
      formatter = logging.Formatter(fmt)
      hdlr = logging.FileHandler(data)
      hdlr.setFormatter(formatter)
      if logLevel:
        try:
          level = eval('logging.%s' % logLevel.upper())
        except AttributeError:
          level = logging.INFO
        hdlr.setLevel(level)
      self.logger.addHandler(hdlr)
    else:
      raise GeneralError('Invalid parameter: data.')

